package com.example.datagramsocket

import android.widget.Toast
import com.binyouwei.udp_lib.factory.MulticastFactory
import com.example.datagramsocket.base.BaseActivity
import com.example.datagramsocket.databinding.ActivityMulticastBinding
import com.example.datagramsocket.utils.MMKVCache

/**
 * 多播/组播
 */
class MulticastActivity : BaseActivity<ActivityMulticastBinding>() {
    val mFactory: MulticastFactory by lazy { MulticastFactory() }
    val multicastTargetIp = javaClass.simpleName

    override fun initView() {
        mBinding.apply {
            mFactory.initUdp()

            targetIp.setText(MMKVCache.getString(multicastTargetIp))
            sureBtn.setOnClickListener {
                val ip = targetIp.text.toString()
                if (ip.isEmpty()) {
                    Toast.makeText(this@MulticastActivity, "请输入目标ip", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }
                mFactory.onReceiveMessageListener(ip) {
                    this@MulticastActivity.runOnUiThread {
                        receiveMessage.text = it
                    }
                }
            }
            sendBtn.setOnClickListener {
                if (targetIp.text.toString().isEmpty()) {
                    Toast.makeText(this@MulticastActivity, "请输入目标ip", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                } else if (sendMessage.text.toString().isEmpty()) {
                    Toast.makeText(this@MulticastActivity, "消息不能为空", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }
                targetIp.text.toString().let {
                    MMKVCache.putString(multicastTargetIp, it)
                    mFactory.sendMessage(it, sendMessage.text.toString())
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mFactory.destroyUdp()
    }
}